import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";
    private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        JSONArray jsonArray = getBookList();
        out.println(jsonArray.toString());
        out.close();
    }

    public JSONArray getBookList() {
        JSONArray jsonArray = new JSONArray();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
  
            Class.forName(DRIVER_CLASS);
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
            statement = connection.createStatement();
 
            String sql = "SELECT number, name, author FROM t_book";
            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("number", resultSet.getString("number"));
                jsonObject.put("name", resultSet.getString("name"));
                jsonObject.put("author", resultSet.getString("author"));
                jsonArray.put(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet!= null) resultSet.close();
                if (statement!= null) statement.close();
                if (connection!= null) connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return jsonArray;
    }
}
